# om.py

"""
One Manga

"""

__author__ = "Lee Chee Meng"

import httplib2
import urllib
from urlparse import urljoin, urlsplit
from os import path
import os
import re
from pyquery import PyQuery as PQ


def save_content(filename, content):
    f = open(filename, 'wb')
    f.write(content)
    f.close()
    
def read_content(filename):
    f = open(filename, 'rb')
    c = f.read()
    f.close()
    return c

    

class MangaDownload(object):
    
    def __init__(self, manga, chapter, local_dir):
        self._base_url = "http://www.onemanga.com/"
        self._url = "%s%s/%s/" % (self._base_url, manga.replace(' ', '_'), chapter)
        print self._url
        self.local_dir = local_dir
        self._chapter_dir = path.join(local_dir, chapter)
        if not path.exists(self._chapter_dir):
            os.mkdir(self._chapter_dir)
        self.client = httplib2.Http('.cache')
        
    def get_data(self, url, encoding=None):
        response, content = self.client.request(url, 'GET')
        try:
            if encoding:
                content = content.decode(encoding)
        except Exception, e:
            print e
        return content
    
    def save_data(self, url, filename):
        response, content = self.client.request(url, 'GET')
        save_content(filename, content)
        return filename
    
    def save_images(self, baseurl, pages, ext):
        for page in pages:
            try:
                filename = page + ext
                self.save_data(urljoin(baseurl, filename),
                               path.join(self._chapter_dir, filename))
            except Exception, e:
                print e
                
    def start(self):
        #url = self._url + "01/"    # get page 01 (not always)
        content = self.get_data(self._url, 'utf8')
        # get the url starts with self._url
        # find the 1st page url
        chapter_path = urlsplit(self._url).path
        pq = PQ(content, parser='html')
        body = PQ('body', pq)
        div = PQ('#chapter-cover', body)
        links = PQ('a', div)
        for link in links:
            url = PQ(link).attr('href')
            if url.startswith(chapter_path):    # shd be the 1st page url
                url = urljoin(self._base_url, url)
                print "1st page", url
                content = self.get_data(url, 'utf8')
                self.parse_content(content, url)
        
    def parse_content(self, content, url):
        """parse, check number of pages in chapter,
           and download images on each page.
        """
        pq = PQ(content, parser='html')
        body = PQ('body', pq)
        selpage = PQ('#id_page_select', body)
        # get all pages in option
        options = PQ('option', selpage)
        pages = [PQ(o).attr('value') for o in options]
        print pages
        # image class manga-page
        img = PQ('img.manga-page', body)
        imgurl = PQ(img).attr('src')
        print imgurl
        imgbase, imgfile = path.split(imgurl)
        # add trailing / back to imgbase , urljoin needs it
        imgbase = imgbase + '/'
        ext = path.splitext(imgfile)[1]
        # not download page itself, the image uses the page name
        #  eg. page 02-03 uses image 02-03.jpg
        # skip credit at the end
        for i in range(len(pages)-1, 0, -1):
            try:
                int(pages[i].replace('-', ''))
                pages = pages[0:i+1]
                break
            except Exception, e:
                continue
        print pages
        self.save_images(imgbase, pages, ext)
        
        
    def _get_test_data(self, filename):
        content = read_content(filename)
        return content.decode('utf8')
        
    def test(self):
        self.parse_content(self._get_test_data('104.html'), '104.html')
        
        
        
if __name__ == '__main__':
    import sys
    a = sys.argv
    if len(a) == 1:    # test
        md = MangaDownload("Full Metal Alchemist", "104", "/home/lcm/interest/comics/fm_alchemist")
        md.test()
    elif len(a) == 4:
        md = MangaDownload(*(a[1:]))
        md.start()
    elif len(a) == 5 and a[4] == 'all':    # all chapters b4 as well
        chapter = int(a[2])
        name, local_dir = a[1], a[3]
        for c in xrange(chapter, 0, -1):
            try:
                md = MangaDownload(name, str(c), local_dir)
                md.start()
            except Exception, e:
                print e
    else:
        print "om.py manga chapter local_dir"
        
        